package com.fingard.dsp.bank.directbank.calyon01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.ReqForeignCurrSingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;

/**
 * 法巴银行sftp
 *
 * @version 1.0
 */
public class CALYON01Base extends DirectBase {
    //解析所用到的
    protected String tag86 = ":86:";
    protected String tag34F = ":34F:";
    protected String tag90D = ":90D:";
    protected String tag90C = ":90C:";
    protected String tag13D = ":13D:";
    //配置
    //protected String splitFlag = "\r\n-";//明细分隔符
    //protected String startFlag = "{4:";//解析内容起始符号
    //protected String endFlag = "-}";//解析内容终止符号
    //86中的字符
    protected String tra = "(TRA)";
    protected String pooling = "POOLING";
    protected String ben = "(BEN)";
    protected String ord = "(ORD)";
    protected String ackFlag = "Status Code";
    protected String askStartFlag = "Received FILE ID";
    protected String askEndFlag = "Bank Reference";
    protected String timeFlag = "Received Date Time";

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String amtCheck(String amt) {
        if (amt.startsWith(".")) {
            amt = "0" + amt;
        }
        if (amt.endsWith(".")) {
            amt = amt + "00";
        }
        amt = keepTwoDecimals(amt);
        return amt;
    }

    /**
     * 去掉小数点后两位的任何元素
     *
     * @param amt
     * @return
     */
    public String keepTwoDecimals(String amt) {
        if (amt.indexOf(".") + 3 < amt.length()) {
            amt = amt.substring(0, amt.indexOf(".") + 3);
        }
        return amt;
    }

    /**
     * 遍历字符串最后一个字母出现的位置
     *
     * @param str 字符串
     * @return
     */
    protected int indexLength(String str) {
        char[] array = str.toCharArray();
        int indexLength = 0;
        for (int i = array.length - 1; i > 0; i--) {
            if (array[i] > 'a' && array[i] < 'z' || array[i] > 'A' && array[i] < 'Z') {
                indexLength = i;
                break;
            }
        }
        return indexLength;
    }


    protected String writeFileContent(ReqSingle p_req1908) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));//添加UTF-8 bom
        sb.append("P,");//record type
        sb.append(p_req1908.reqHeader.reqSeqID).append(",");//批次号
        sb.append(p_req1908.reqHeader.reqSeqID).append(",");//流水号
        sb.append(p_req1908.singleDetail.payAct).append(",");//支付账号
        sb.append("BNPACNSHXXX").append(",");//支付账号SWIFT CODE 默认BNPACNSHXXX
        sb.append(Format.Date10Format3.format(Format.Date10Format.parse(p_req1908.singleDetail.payDate))).append(",");//交易时间
        sb.append("RMB,");//Payment Type
        sb.append("02,");//Transaction Code 01 - Vendor 02 - Salary
        sb.append(StringHelper.hasAnyChar(p_req1908.singleDetail.payCur) ? convertCurToBank(p_req1908.singleDetail.payCur) : "CNY").append(",");//Payment Currency
        sb.append(p_req1908.singleDetail.payAmount).append(",");//Payment Amount
        sb.append(",");//Beneficiary Bank SWIFT code
        sb.append(p_req1908.singleDetail.cnapsCode).append(",");//Beneficiary Bank Party Identifier
        sb.append(p_req1908.singleDetail.recBankName).append(",");//Beneficiary Bank Name
        sb.append(",");//Beneficiary Bank Address1
        sb.append(",");//Beneficiary Bank Address2
        sb.append("CN,");//Beneficiary Bank Address3
        sb.append(p_req1908.singleDetail.recAct).append(",");//Beneficiary Account Number
        sb.append(p_req1908.singleDetail.recName).append(",");//Beneficiary Name
        sb.append(",");//Beneficiary Address 1
        sb.append(",");//Beneficiary Address 2
        sb.append(",");//Beneficiary Address 3
        sb.append("CN,");//Beneficiary Address - Country
        sb.append(",");//Beneficiary Resident/Non-Resident Flag
        sb.append("CN,");//Beneficiary Identification Type
        sb.append(",");//Beneficiary Identification
        sb.append(",");//Intermediary Bank SWIFT code
        sb.append(",");//Intermediary Bank Name
        sb.append(",");//Intermediary Bank Address1
        sb.append(",");//Intermediary Bank Address2
        sb.append(",");//Intermediary Bank Address3
        sb.append(",");//Recipient Email Address1
        sb.append(",");//Recipient Email Address2
        sb.append(p_req1908.singleDetail.askNumber).append(",");//Payment Details 1
        sb.append(",");//Payment Details 2
        sb.append(",");//Payment Details 3
        sb.append(",");//Payment Details 4
        sb.append("321000,");//Purpose Code
        sb.append("OUR,");//Charge Bearer
        sb.append(",");//Batch Booking
        sb.append(",");//Delivery Method
        sb.append(",");//Deliver To
        sb.append(",");//Clearing Zone
        sb.append(",").append("\n");//Filler
        sb.append("I,");//Invoice Block Record Type
        sb.append(p_req1908.singleDetail.askNumber).append(",");//Invoice Block Invoice Number
        sb.append(Format.Date10Format3.format(Format.Date10Format.parse(p_req1908.singleDetail.payDate))).append(",");//Invoice Block Invoice Date
        sb.append(p_req1908.singleDetail.payAmount);//Invoice Amount
        sb.append(p_req1908.singleDetail.description);//Descriptions
        return sb.toString();
    }

    /**
     * 写入文件
     *
     * @param content
     * @param fullName
     * @return
     */
    protected boolean exportContentToFile(String content, String fullName) {
        if (StringHelper.isNullOrEmpty(content) || StringHelper.isNullOrEmpty(fullName)) {
            return false;
        }
        try {
            FileHelper.writeFile(fullName, content, getCharset());
            WriteBankLogLn2("写入文件：" + fullName + ",文件内容 \r\n" + content);
        } catch (Exception e) {
            WriteBankLogLn2("写入文件：" + fullName + "失败!");
            e.printStackTrace();
            return false;
        }
        return FileHelper.existFile(fullName);
    }

    /**
     * 地址处理
     *
     * @param xmlWriter
     * @param address
     * @param countryCode
     */
    private void addressDealWith(XmlTextWriter xmlWriter, String address, String countryCode, StringBuilder addLine) {
        String twnNm = "";
        if (StringHelper.hasAnyChar(address)) {
            //解析地址和城镇信息
            String addr = address.contains("##") ? address.substring(0, address.indexOf("##")) : address;
            String trwn = address.contains("##") ? address.substring(address.indexOf("##") + 2).replaceAll("##", " ") : "";
            //拼接获取长度
            String payAddr = new StringBuilder(trwn).append(" ").append(addr).toString();
            if (StringHelper.hasAnyChar(payAddr)) {
                if (payAddr.length() > 30) {
                    twnNm = payAddr.substring(0, 30);
                    addLine.append(payAddr.substring(30));
                } else {
                    twnNm = payAddr;
                }
            }
        }
        if (StringHelper.hasAnyChar(twnNm) || StringHelper.hasAnyChar(countryCode) || StringHelper.hasAnyChar(addLine.toString())) {
            xmlWriter.writeStartElement("PstlAdr");
        }
        if (StringHelper.hasAnyChar(twnNm)) {
            xmlWriter.writeElementString("TwnNm", twnNm);
        }
        if (StringHelper.hasAnyChar(countryCode)) {
            xmlWriter.writeElementString("Ctry", "C".equals(countryCode) ? "CN" : countryCode);
        }
        if (StringHelper.hasAnyChar(addLine.toString())) {
            xmlWriter.writeElementString("AdrLine", addLine.toString());
        }
        if (StringHelper.hasAnyChar(twnNm) || StringHelper.hasAnyChar(countryCode) || StringHelper.hasAnyChar(addLine.toString())) {
            xmlWriter.writeEndElement();
        }
    }

    protected String FeeBearer(String costmode) {
        if ("OUR".equals(costmode)) {
            costmode = "DEBT";
        } else if ("BEN".equals(costmode)) {
            costmode = "CRED";
        } else if ("SHA".equals(costmode)) {
            costmode = "SHAR";
        }
        return costmode;
    }

    /**
     * 获取ack状态并写入文件
     *
     * @param ackFilePath
     * @param payDate
     * @param rspStatus
     * @return
     * @throws Exception
     */
    protected void getAckStatus(String ackFilePath, String payDate, String[] rspStatus, String level) throws Exception {
        String ackFile = ackFilePath + File.separator + payDate + File.separator
                + "ACK" + File.separator + rspStatus[0] + File.separator + rspStatus[0] + "_" + level + ".txt";
        String contents = rspStatus[0] + "|" + rspStatus[1] + "|" + rspStatus[2] + "|";
        //写入文件
        FileHelper.appendFile(ackFile, contents, getCharset());
    }

    /**
     * 获取支持的查询日期
     *
     * @param sDate
     * @param eDate
     * @return
     */
    protected String[] getQueryDate(String sDate, String eDate) throws Exception {
        String[] dateAry = new String[]{sDate, eDate};
        String hisTransSupDate = getBankConfig().getValueAsString("hisTransSupDate");
        //增加历史明细支持查询日期
        if (StringHelper.hasAnyChar(hisTransSupDate) && hisTransSupDate.length() == 8) {
            //判断起始日
            Date avaiDate = Format.Date8Format.parse(hisTransSupDate);
            Date startDate = Format.Date8Format.parse(dateAry[0]);
            Date endDate = Format.Date8Format.parse(dateAry[1]);
            if (endDate.after(avaiDate)) {
                if (startDate.before(avaiDate)) {
                    dateAry[0] = hisTransSupDate;
                }
            } else {
                dateAry[0] = hisTransSupDate;
                dateAry[1] = hisTransSupDate;
            }
        }
        return dateAry;
    }
}

